package org.totoro.consumer.config;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.GetResponse;

import java.util.Scanner;

/**
 * @author YHL
 * @version V1.0
 * @Description: 手动拉去消息
 * @date 2018-05-26
 */
public class ManuallyPullMessage {

    private final static String QUEUE_NAME = "pull_queue";


    /**
     * 手动获取队列消息
     *
     * @param argv
     * @throws Exception
     */
    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        //设置登录账号
        factory.setHost("127.0.0.1");
        factory.setPort(5672);
        factory.setUsername("admin");
        factory.setPassword("admin");
        //链接服务器
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        //定义一个队列
        boolean duiable = false;//持久化
        boolean exclusive = false;//排他队列
        boolean autoDelete = false;//没有consumer时，队列是否自动删除
        channel.queueDeclare(QUEUE_NAME, duiable, exclusive, autoDelete, null);


        //接收消息
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
        boolean autoAck = true; //自动应答


        System.out.println("输入回车获取消息，退出输入 x ");
        String message = "";
        GetResponse resp;
        do {
            Scanner scanner = new Scanner(System.in);
            scanner.nextLine();
            resp = channel.basicGet(QUEUE_NAME, autoAck);
            if (resp == null) {
                System.out.println(QUEUE_NAME + " 队列无消息");
                continue;
            }
            message = new String(resp.getBody(), "UTF-8");
            System.out.println(String.format(" [x] Recv Count %s , msg = %s;"
                    , resp.getMessageCount()
                    , message));
        } while (!"x".equals(message));
    }

}
